package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.Employee;
import model.EmployeeRole;
import model.Enterprise;
import model.UserAccount;
import model.type.EmployeeRoleType;
import util.Log;
import validator.EmployeeRoleValidator;
import web.JSONMessage;
import db.ImbiConnection;
import facade.EmployeeFacade;

public class EmployeeController extends HttpServlet{
	
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		UserAccount u = (UserAccount) request.getSession().getAttribute("user");
		try{
			if(u != null){			
				Enterprise e = ImbiConnection.getEnterpriseDAO().find(Integer.parseInt(request.getParameter("enterprise")));
				if(e != null){
					request.setAttribute("roleTypes", EmployeeRoleType.getAll());
					request.setAttribute("enterprise", e);
					request.setAttribute("persons", ImbiConnection.getPersonDAO().findAll());
					request.getRequestDispatcher("/WEB-INF/employee.jsp").forward(request, response);					
				}
			}
		} catch(Exception e){
			
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		UserAccount u = (UserAccount) request.getSession().getAttribute("user");
		if(u != null){	
			if(request.getParameter("delete")!= null){
				deleteEmployeeRole(request, response);
			} else addEmployeeRole(request);
		}
	}

	private void deleteEmployeeRole(HttpServletRequest request,
			HttpServletResponse response) throws IOException {			
			// Also deletes the employee, if no roles are left
			int id = Integer.parseInt(request.getParameter("id"));
			EmployeeRole role = ImbiConnection.getEmployeeRoleDAO().find(id);
			if(role != null){				
				Employee e = ImbiConnection.getEmployeeDAO().find(role.getEmployee());
				ImbiConnection.getEmployeeRoleDAO().delete(role);				
				ArrayList<EmployeeRole> roles = ImbiConnection.getEmployeeRoleDAO().findAllByEmployee(e);
				if(roles.size() == 0){ 
					EmployeeFacade.deleteEmployee(e);
					response.getWriter().write(JSONMessage.message("Role deleted. Employee deleted, because it had no roles left."));	
				} else response.getWriter().write(JSONMessage.message("Role deleted."));		
				Log.write(((UserAccount) request.getSession().getAttribute("user")).getUsername()+" deleted employee "+id);
			} else response.getWriter().write(JSONMessage.errorMessage("Illegal parameter"));
			
			
			
	}

	private void addEmployeeRole(HttpServletRequest request) {
		EmployeeRoleValidator validator = new EmployeeRoleValidator(
			request.getParameter("person"),
			request.getParameter("enterprise"),
			request.getParameter("role_type")
		);
		if(validator.isLogicallyValid()){ 
			Enterprise e = ImbiConnection.getEnterpriseDAO().find(validator.getEnterprise());
			ArrayList<Employee> employees = ImbiConnection.getEmployeeDAO().findAllByEnterprise(e);				
			Employee emp = searchEmployeeByPerson(validator, employees);
			if(emp == null){ 
				emp = createNewEmployee(validator, e); 
				Log.write(((UserAccount) request.getSession().getAttribute("user")).getUsername()+" created employee "+emp);
			}
			EmployeeRole role = new EmployeeRole(
				0,
				emp.getId(),
				validator.getRole().getId(),
				true
			);				
			ImbiConnection.getEmployeeRoleDAO().insert(role);
		}
	}

	private Employee createNewEmployee(EmployeeRoleValidator validator,
			Enterprise e) {
		Employee emp;
		emp = new Employee(0, validator.getPerson(), validator.getEnterprise(), 0, true);
		ImbiConnection.getEmployeeDAO().insert(emp);
		// get the new ID		
		emp = searchEmployeeByPerson(validator, ImbiConnection.getEmployeeDAO().findAllByEnterprise(e));		
		return emp;
	}

	private Employee searchEmployeeByPerson(EmployeeRoleValidator validator,
			ArrayList<Employee> emps) {
		Employee emp = null;
		for(Employee employee: emps){
			if(employee.getPerson() == validator.getPerson()){ 
				emp = employee;
				break;
			}
		}
		return emp;
	}
}
